<?php

namespace App\Repositories\Eloquent\Acl;

use Route,DB;
use App\Repositories\Eloquent\Repository;

class RoleRepository extends Repository
{

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Acl\Role';
    }

    /**
     * role列表
     *
     * @param string $query
     * @return mixed
     */
    public function index($query = '')
    {
        // 获取分页数据
        if (!$query) {
            $result = $this->model
                ->orderBy('created_at', 'desc');
        } else {
            // 若有查询参数
            $result = $this->model
                ->where('name', 'like', "%$query%");
        }

        return $result;
    }

    /**
     * 查找指定role
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function show($id)
    {   
        $role = $this->find($id);        
        if (!$role) 
            return $this->responseFail(404);
        return $role;
    }

    /**
     * 存储role
     *
     * @param $request
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function store($request)
    {
        $role = $this->create([
            'name' => $request->name,
            'guard_name' => 'admin'
        ]);
        // 若Role创建成功且存在permissions
        if ($result = !!$role) {
            $role->givePermissionTo($request->permissions);
        }
        if( $result )
            return $this->responseSuccess('添加角色成功', $role, route('system.role.index'));
        
        return $this->responseFail(500, '添加角色失败');
    }

    /**
     * 更新role
     *
     * @param $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function renew($request, $id)
    {
        DB::beginTransaction();
        try {
            $result = $this->update([
                'name' => $request->name
            ], $id);
            if ($result) {
                // 更新Role与Permission的中间表
                $this->find($id)->syncPermissions($request->permissions);
            }
            DB::commit();
            return $this->responseSuccess('更新角色成功', $this->find($id));

        } catch (Exception $e) {
            DB::rollback();
            return $this->responseFail(500, '更新角色失败');
        } 
        
    }

    /**
     * 删除role
     *
     * @param $ids
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function destroy($ids)
    {
        if (!!$this->delete($ids))
            return $this->responseSuccess('删除角色成功');

        return $this->responseFail(500, '删除角色失败');
    }

}